<?php
/**
 * 服务器管理类
 * 
 * @author ShuangYa
 * @package APIGateway
 * @category Library
 * @link https://www.sylingd.com/
 * @copyright Copyright (c) 2018 ShuangYa
 * @license https://www.sylibs.com/go/apigateway/license
 */
namespace ag\library;

use yesf\library\database\Database;
use ag\model\Service;

class ServerManager {
	/**
	 * 添加服务器
	 * 
	 * @access public
	 * @param int $service_id 服务ID
	 * @param string $ip
	 * @param int $port
	 * @param int $weight 权重
	 */
	public static function add($service_id, $ip, $port, $weight = 100) {
		Service::getInstance()->add([
			'service' => $service_id,
			'ip' => $ip,
			'port' => $port,
			'weight' => $weight
		]);
	}
	/**
	 * 判断是否存在
	 * 
	 * @access public
	 * @param int $service_id 服务ID
	 * @param string $ip
	 * @param int $port
	 */
	public static function exists($service_id, $ip, $port) {
		$me = Service::getInstance()->get([
			'service' => $service_id,
			'ip' => $ip,
			'port' => $port
		]);
		return $me !== NULL;
	}
	/**
	 * 移除服务器
	 * 
	 * @access public
	 * @param int $service_id 服务ID
	 * @param string $ip
	 * @param int $port
	 */
	public static function remove($service_id, $ip, $port) {
		Service::getInstance()->del([
			'service' => $service_id,
			'ip' => $ip,
			'port' => $port
		]);
	}
	/**
	 * 设置服务器权重
	 * 
	 * @access public
	 * @param int $service_id 服务ID
	 * @param string $ip
	 * @param int $port
	 * @param int $weight 权重
	 */
	public static function setWeight($service_id, $ip, $port, $weight = 100) {
		Service::getInstance()->set([
			'weight' => $weight
		], [
			'service' => $service_id,
			'ip' => $ip,
			'port' => $port
		]);
	}
	/**
	 * 获取某一服务下的全部服务器
	 * 
	 * @access public
	 * @param int $service_id 服务ID
	 * @return array
	 */
	public static function getAll($service_id) {
		return Service::getInstance()->list([
			'service' => $service_id
		]);
	}
	/**
	 * 随机获取一个服务器
	 * 
	 * @access public
	 * @param int $service_id 服务ID
	 * @return array
	 */
	public static function rand($service_id) {
		$list = self::getAll($service_id);
		$total = count($list);
		if ($total === 0) {
			return NULL;
		} elseif ($total === 1) {
			return $list[0];
		} else {
			// TODO: 带权随机
			return $list[mt_rand(0, $total - 1)];
		}
	}
}